# -*- coding: utf-8 -*-
from src       import utils
from src.types import Account

from fastapi           import Request, APIRouter, HTTPException
from fastapi.responses import JSONResponse


index = APIRouter()


@index.post("/login")
async def login(request: Request):
    if request.cookies.get("id") != None:
        return JSONResponse({"id": int(request.cookies.get("id"))}, status_code = 200)

    data: dict  = await utils.parse.dictionary(request = request)
    keys: tuple = ("email", "password")

    if not data:
        raise HTTPException(400, detail = "Failed to get passed values, specify them in JSON format")

    if (missing := [key for key in keys if key not in data]) != []:
        raise HTTPException(400, detail = f"No values found: {', '.join(missing)}")

    if (nullable := [key for key in keys if (data[key] == None or data[key].strip() == "")]) != []:
        raise HTTPException(400, detail = f"Values are incorrect for: {', '.join(nullable)}")

    account = await Account.get_by_auth(data["email"], data["password"], request.app.database)

    if not account:
        raise HTTPException(401, detail = "Invalid email or password")
    
    response = JSONResponse({"id": account.id}, status_code = 200)
    response.set_cookie("id", account.id)

    return response


@index.post("/registration")
async def registration(request: Request):
    try:
        if request.cookies.get("id") != None:
            raise HTTPException(403, detail = "Already logged in")

        data: dict  = await utils.parse.dictionary(request = request)
        keys: tuple = ("firstName", "lastName", "email", "password")

        if not data:
            raise HTTPException(400, detail = "Failed to get passed values, specify them in JSON format")

        if (missing := [key for key in keys if key not in data]) != []:
            raise HTTPException(400, detail = f"No values found: {', '.join(missing)}")

        if (nullable := [key for key in keys if (data[key] == None or data[key].strip() == "")]) != []:
            raise HTTPException(400, detail = f"Values are incorrect for: {', '.join(nullable)}")

        if not utils.check.is_email(data['email']):
            raise HTTPException(400, detail = "Invalid email")

        database = request.app.database
        exists   = await Account.exists(database, email = data["email"])

        if exists:
            raise HTTPException(409, detail = "An account with this email already exists")

        # exists = await Account.get_by(database, password = data["password"])

        # if exists:
        #     raise HTTPException(409, detail = f"Аккаунт с данным паролем уже существует, попробуйте войти под логином ({exists.email})")

        account = await Account.create(database, **data)

        response = JSONResponse(account("id", "firstName", "lastName", "email"), status_code = 201)
        response.set_cookie("id", account.id)

        return response
    except Exception as e:
        raise HTTPException(501, detail = f"{e.__class__.__name__}: {str(e)}")
